// Database.executeBatch(new SalePerformanceDataCalcBatch(System.today().year()+'年','1','MKSW') , 1);

/*
    List<String> companys = 'GDMK,MKSW,MKSY,BJMK,YNMK,HBMK,JLMK,GZMK,NMMK,CQZT,XJMK,SDMK,SHMK,SXMK'.split(',');
    for(String c : companys ){
        Database.executeBatch(new SalePerformanceDataCalcBatch('2020年','2',c),1);
    }

*/
//按公司进行汇总数据 
global class SalePerformanceDataCalcBatch implements Database.Batchable<AggregateResult> {
    
    public String year ;
    public String quarter;
    public String company ; 

    public Boolean isIncrease = false;

   // public List<String> companys ; 

    global SalePerformanceDataCalcBatch(){

    }
    global SalePerformanceDataCalcBatch(String year ,String quarter,String company ){

        this.year = year;
        this.quarter = quarter;
        this.company =  company;

       // companys = Label.PerformanceImportCompany.split(',',-1);

    }
     global SalePerformanceDataCalcBatch(String year ,String quarter,String company, Boolean isIncrease ){

        this.year = year;
        this.quarter = quarter;
        this.company =  company;
        this.isIncrease = isIncrease;
       // companys = Label.PerformanceImportCompany.split(',',-1);

    }
    global void init(){
        this.year  = '';
        this.quarter = '';
        Integer m = System.today().month();
        if(m > 3 && m <=6 ) this.quarter = '1';
        if(m > 6 && m <=9)this.quarter = '2';
        if(m > 9 && m <=12)this.quarter = '3';
        if(m >=1 && m <4 )this.quarter = '4';
        this.year = this.quarter == '4' ? (System.today().year()-1)+'年': System.today().year()+'年';

       // companys = Label.PerformanceImportCompany.split(',',-1);

    }
    global Iterable<AggregateResult> start(Database.batchableContext info){
       if(this.year == null || this.quarter == null) init();

       if(this.isIncrease)return [select  EmployeeNumber__c,Company__c  from SalesPerformanceDataSheet__c where 
       Year__c=:this.year and EmployeeNumber__c != null and Company__c =:this.company  group by EmployeeNumber__c,Company__c ];


       return [select  EmployeeNumber__c,Company__c  from SalesPerformanceDataSheet__c where 
       Year__c=:this.year and Quarter__c =:this.quarter and EmployeeNumber__c != null and Company__c =:this.company  group by EmployeeNumber__c,Company__c ];


    }
   


    global void execute(Database.BatchableContext BC,List<AggregateResult> spList ) {


            // for (SalesPerformanceDataSheet__c  sp: spList) {

            //     SalePerformanceDataCalcUtil.calcToResult(sp.EmployeeNumber__c, this.year, this.quarter);
            // }

            String wono = '';
            String company = '';
            for(AggregateResult arg : spList){

                wono = (String)arg.get('EmployeeNumber__c');
                company = (String)arg.get('Company__c');
                break;
            }

            List<SalesPerformanceDataSheet__c> sumList = new List<SalesPerformanceDataSheet__c>();
            Id baseRegentId = Utils.getRecordTypeIdByDevNameAndObjName('ReagentPerformanceSum', 'SalesPerformanceDataSheet__c');

            //如果是单独计算年度的增量数据 
            if(isIncrease){
                
                Id agentId = Utils.getRecordTypeIdByDevNameAndObjName('AgentIncrementPerformanceSum', 'SalesPerformanceDataSheet__c');

                sumList.addAll(sumAegentYear(wono,company,agentId,baseRegentId,this.year));

                Id annualId = Utils.getRecordTypeIdByDevNameAndObjName('AnnualIncrementPerformanceSum', 'SalesPerformanceDataSheet__c');

                sumList.addAll(sumRegentYear(wono,company,annualId,baseRegentId,this.year));

                List<Id> yRts = new List<Id>{agentId,annualId};

                delete [select Id from SalesPerformanceDataSheet__c where 
                EmployeeNumber__c =:wono and RecordTypeId in: yRts  and Year__c=:this.year  and  Company__c=:company];

                insert  sumList; 

                System.debug(sumList);


                return ;

            }
            //删除已经存在的
           

            //计算新的  
            //仪器绩效汇总

            Id equipId = Utils.getRecordTypeIdByDevNameAndObjName('InstrumentPerformanceSum', 'SalesPerformanceDataSheet__c');

            sumList.addAll(sumBaseEquip(wono,company,equipId,new List<String>{'InstrumentPerformance','InstrumentPerformanceAdjust'},this.year,this.quarter));
            
            //自产试剂增量汇总
            Id regentIncreaseId = Utils.getRecordTypeIdByDevNameAndObjName('ReagentIncrementalPerformanceSum', 'SalesPerformanceDataSheet__c');

            sumList.addAll(sumBaseRegentIncrease(wono,company,regentIncreaseId,new List<String>{'ReagentIncrementalPerformance','ReagentIncrementalPerformanceAdjust'},this.year,this.quarter));
            //试剂基本绩效汇总


            sumList.addAll(sumBaseRegent(wono,company,baseRegentId,new List<String>{'ReagentPerformance','ReagentBudgetAdjust'},this.year,this.quarter));

            /*
            if(quarter == '4'){

                //年度代理 
                Id agentId = Utils.getRecordTypeIdByDevNameAndObjName('AgentIncrementPerformanceSum', 'SalesPerformanceDataSheet__c');

                sumList.addAll(sumRegent(wono,company,agentId,new List<String>{'AgentIncrementPerformance','AgentIncrementPerformanceAdjust'},this.year));

                //年度增量
                Id annualId = Utils.getRecordTypeIdByDevNameAndObjName('AnnualIncrementPerformanceSum', 'SalesPerformanceDataSheet__c');

                sumList.addAll( sumRegent(wono,company,annualId,new List<String>{'AnnualIncrementPerformance','AnnualIncrementPerformanceAdjust'},this.year));

            }
            */
            



            delete [select Id from SalesPerformanceDataSheet__c where 
                EmployeeNumber__c =:wono and RecordType.DeveloperName like '%Sum' and Year__c=:this.year and Quarter__c=:this.quarter  and  Company__c=:company];


            insert  sumList; 

           



    }

    global void finish(Database.BatchableContext BC) {

    }


     public List<SalesPerformanceDataSheet__c> sumRegentYear(String wono, String company,String recordId ,String rts ,String year  ){

        System.debug(wono);
        System.debug(company);
        System.debug(recordId);
        System.debug(rts);
        System.debug(year);
        List<SalesPerformanceDataSheet__c> sumList = new List<SalesPerformanceDataSheet__c>();

        for(AggregateResult arg : [select  Company__c , EmployeeNumber__c,Name__c,JobCategory__c,SalesMarket__c ,

            sum(ActualSales__c) ActualSales__c, sum(ActualSalesQ1__c) ActualSalesQ1__c, sum(ActualSalesQ2__c) ActualSalesQ2__c,sum(ActualSalesQ3__c) ActualSalesQ3__c, sum(ActualSalesQ4__c) ActualSalesQ4__c ,

            sum(BudgetSales__c) BudgetSales__c , sum(BudgetSalesQ1__c) BudgetSalesQ1__c ,sum(BudgetSalesQ2__c) BudgetSalesQ2__c ,sum(BudgetSalesQ3__c) BudgetSalesQ3__c,sum(BudgetSalesQ4__c) BudgetSalesQ4__c ,

            sum(LastYearSalesVolume__c) LastYearSalesVolume__c , sum(LastYearSalesVolumeQ1__c) LastYearSalesVolumeQ1__c ,sum(LastYearSalesVolumeQ2__c) LastYearSalesVolumeQ2__c ,sum(LastYearSalesVolumeQ3__c) LastYearSalesVolumeQ3__c,sum(LastYearSalesVolumeQ4__c) LastYearSalesVolumeQ4__c 

             from SalesPerformanceDataSheet__c where Year__c =:year and Company__c =:company

              and RecordTypeId =:rts and NotActive__c = false and  EmployeeNumber__c =:wono 

              and ReagentCategory__c like '%迈克%'
              
             group by   Company__c , EmployeeNumber__c,Name__c,JobCategory__c,SalesMarket__c
                
             ] ){

             SalesPerformanceDataSheet__c sum = generSumData(arg,recordId,year,quarter);
             sum.ActualSales__c =sum(new List<Decimal>{sum.ActualSalesQ1__c , sum.ActualSalesQ2__c ,sum.ActualSalesQ3__c , sum.ActualSalesQ4__c }) ;
             sum.BudgetSales__c =sum(new List<Decimal>{sum.BudgetSalesQ1__c , sum.BudgetSalesQ2__c ,sum.BudgetSalesQ3__c , sum.BudgetSalesQ4__c }) ;
             sum.LastYearSalesVolume__c =sum(new List<Decimal>{sum.LastYearSalesVolumeQ1__c , sum.LastYearSalesVolumeQ2__c ,sum.LastYearSalesVolumeQ3__c , sum.LastYearSalesVolumeQ4__c }) ;



            sumList.add(sum);
           
        }
        return sumList;

    }
     public List<SalesPerformanceDataSheet__c> sumAegentYear(String wono, String company,String recordId ,String  rts ,String year  ){

        List<SalesPerformanceDataSheet__c> sumList = new List<SalesPerformanceDataSheet__c>();

        for(AggregateResult arg : [select  Company__c , EmployeeNumber__c,Name__c,JobCategory__c,SalesMarket__c ,

            sum(ActualSales__c) ActualSales__c, sum(ActualSalesQ1__c) ActualSalesQ1__c, sum(ActualSalesQ2__c) ActualSalesQ2__c,sum(ActualSalesQ3__c) ActualSalesQ3__c, sum(ActualSalesQ4__c) ActualSalesQ4__c ,

            sum(BudgetSales__c) BudgetSales__c , sum(BudgetSalesQ1__c) BudgetSalesQ1__c ,sum(BudgetSalesQ2__c) BudgetSalesQ2__c ,sum(BudgetSalesQ3__c) BudgetSalesQ3__c,sum(BudgetSalesQ4__c) BudgetSalesQ4__c ,

            sum(LastYearSalesVolume__c) LastYearSalesVolume__c , sum(LastYearSalesVolumeQ1__c) LastYearSalesVolumeQ1__c ,sum(LastYearSalesVolumeQ2__c) LastYearSalesVolumeQ2__c ,sum(LastYearSalesVolumeQ3__c) LastYearSalesVolumeQ3__c,sum(LastYearSalesVolumeQ4__c) LastYearSalesVolumeQ4__c 

             from SalesPerformanceDataSheet__c where Year__c =:year and Company__c =:company

              and RecordTypeId  =: rts and NotActive__c = false and  EmployeeNumber__c =:wono 

              and (not ReagentCategory__c like '%迈克%')
              
             group by   Company__c , EmployeeNumber__c,Name__c,JobCategory__c,SalesMarket__c
                
             ] ){

             SalesPerformanceDataSheet__c sum = generSumData(arg,recordId,year,quarter);
             sum.ActualSales__c =sum(new List<Decimal>{sum.ActualSalesQ1__c , sum.ActualSalesQ2__c ,sum.ActualSalesQ3__c , sum.ActualSalesQ4__c }) ;
             sum.BudgetSales__c =sum(new List<Decimal>{sum.BudgetSalesQ1__c , sum.BudgetSalesQ2__c ,sum.BudgetSalesQ3__c , sum.BudgetSalesQ4__c }) ;
             sum.LastYearSalesVolume__c =sum(new List<Decimal>{sum.LastYearSalesVolumeQ1__c , sum.LastYearSalesVolumeQ2__c ,sum.LastYearSalesVolumeQ3__c , sum.LastYearSalesVolumeQ4__c }) ;

            sumList.add(sum);
           
        }
        return sumList;

    }

    private Decimal sum(List<Decimal> numbers ){
        Decimal t= 0;
        for (Decimal d  :numbers ) {
            if(d ==  null )continue;
            t+=d;
        }
        return  t ;
    }

    /*
    public List<SalesPerformanceDataSheet__c> sumRegent(String wono, String company,String recordId ,List<String> rts ,String year ){

        List<SalesPerformanceDataSheet__c> sumList = new List<SalesPerformanceDataSheet__c>();

        for(AggregateResult arg : [select   Company__c , EmployeeNumber__c,Name__c,JobCategory__c,SalesMarket__c,
            
            sum(ActualSales__c) ActualSales__c, 
            sum(LastYearSalesVolume__c) LastYearSalesVolume__c , 
            sum(BudgetSales__c) BudgetSales__c  
            
            from SalesPerformanceDataSheet__c where Year__c =:year  and Company__c =:company

              and RecordType.DeveloperName in:rts and NotActive__c = false  and EmployeeNumber__c =:wono 
              
             group by  Company__c , EmployeeNumber__c,Name__c,JobCategory__c,SalesMarket__c
             ] ){
           
             SalesPerformanceDataSheet__c sum = generSumData(arg,recordId,year,null );
            sumList.add(sum);
        
        }
          return sumList;

    }
    */

   public List<SalesPerformanceDataSheet__c> sumBaseRegent(String wono, String company,String recordId ,List<String> rts ,String year ,String quater  ){

        List<SalesPerformanceDataSheet__c> sumList = new List<SalesPerformanceDataSheet__c>();
        for(AggregateResult arg : [select  Company__c , EmployeeNumber__c,Name__c,JobCategory__c,SalesMarket__c,ReagentCategory__c ,
            sum(ActualSales__c) ActualSales__c, sum(ActualSalesQ1__c) ActualSalesQ1__c, sum(ActualSalesQ2__c) ActualSalesQ2__c,sum(ActualSalesQ3__c) ActualSalesQ3__c, sum(ActualSalesQ4__c) ActualSalesQ4__c ,
            sum(BudgetSales__c) BudgetSales__c , sum(BudgetSalesQ1__c) BudgetSalesQ1__c ,sum(BudgetSalesQ2__c) BudgetSalesQ2__c ,sum(BudgetSalesQ3__c) BudgetSalesQ3__c,sum(BudgetSalesQ4__c) BudgetSalesQ4__c ,
            sum(LastYearSalesVolume__c) LastYearSalesVolume__c , sum(LastYearSalesVolumeQ1__c) LastYearSalesVolumeQ1__c ,sum(LastYearSalesVolumeQ2__c) LastYearSalesVolumeQ2__c ,sum(LastYearSalesVolumeQ3__c) LastYearSalesVolumeQ3__c,sum(LastYearSalesVolumeQ4__c) LastYearSalesVolumeQ4__c 

             from SalesPerformanceDataSheet__c where Year__c =:year and Quarter__c =:quater and Company__c =:company

              and RecordType.DeveloperName in:rts and NotActive__c = false and  EmployeeNumber__c =:wono 
              
             group by   Company__c , EmployeeNumber__c,Name__c,JobCategory__c,SalesMarket__c, ReagentCategory__c
                
             ] ){

             SalesPerformanceDataSheet__c sum = generSumData(arg,recordId,year,quarter);
            sumList.add(sum);
           
        }
        return sumList;

    }

    public List<SalesPerformanceDataSheet__c> sumBaseEquip(String wono, String company,String recordId ,List<String> rts ,String year ,String quater ){

        List<SalesPerformanceDataSheet__c> sumList = new List<SalesPerformanceDataSheet__c>();
        for(AggregateResult arg : [select Company__c , EmployeeNumber__c,Name__c,JobCategory__c,SalesMarket__c,InstrumentClasses__c , 

            sum(BudgetQuantity__c) BudgetQuantity__c,sum(BudgetQuantityQ1__c) BudgetQuantityQ1__c, sum(BudgetQuantityQ2__c) BudgetQuantityQ2__c,sum(BudgetQuantityQ3__c) BudgetQuantityQ3__c, sum(BudgetQuantityQ4__c) BudgetQuantityQ4__c ,
            sum(ActualQuantity__c) ActualQuantity__c , sum(ActualQuantityQ1__c) ActualQuantityQ1__c ,sum(ActualQuantityQ2__c) ActualQuantityQ2__c ,sum(ActualQuantityQ3__c) ActualQuantityQ3__c,sum(ActualQuantityQ4__c) ActualQuantityQ4__c 

             from SalesPerformanceDataSheet__c where Year__c =:year and Quarter__c =:quarter and Company__c =:company

              and RecordType.DeveloperName in:rts and NotActive__c = false  and  EmployeeNumber__c =:wono 
              
             group by    Company__c , EmployeeNumber__c,Name__c,JobCategory__c,SalesMarket__c,InstrumentClasses__c
                
             ] ){
            
            SalesPerformanceDataSheet__c sum = generSumData(arg,recordId,year,quarter);
            sumList.add(sum);
        }
        return sumList;

    }

    public List<SalesPerformanceDataSheet__c> sumBaseRegentIncrease(String wono, String company,String recordId ,List<String> rts ,String year ,String quater ){

        
        List<SalesPerformanceDataSheet__c> sumList = new List<SalesPerformanceDataSheet__c>();
        for(AggregateResult arg : [select   Company__c , EmployeeNumber__c,Name__c,JobCategory__c,SalesMarket__c,IncrementalCcategory__c,Category__c,
            sum(ActualSales__c) ActualSales__c, sum(ActualSalesQ1__c) ActualSalesQ1__c, sum(ActualSalesQ2__c) ActualSalesQ2__c,sum(ActualSalesQ3__c) ActualSalesQ3__c, sum(ActualSalesQ4__c) ActualSalesQ4__c ,
            sum(LastYearSalesVolume__c) LastYearSalesVolume__c , sum(LastYearSalesVolumeQ1__c) LastYearSalesVolumeQ1__c ,sum(LastYearSalesVolumeQ2__c) LastYearSalesVolumeQ2__c ,sum(LastYearSalesVolumeQ3__c) LastYearSalesVolumeQ3__c,sum(LastYearSalesVolumeQ4__c) LastYearSalesVolumeQ4__c 
             from SalesPerformanceDataSheet__c where Year__c =:year and Quarter__c =:quater and Company__c =:company

              and RecordType.DeveloperName in:rts and NotActive__c = false and  EmployeeNumber__c =:wono 
              
             group by  Company__c , EmployeeNumber__c,Name__c,JobCategory__c,SalesMarket__c,IncrementalCcategory__c,Category__c
                
             ] ){
          
            SalesPerformanceDataSheet__c sum = generSumData(arg,recordId,year,quarter);
            sumList.add(sum);

        }
        return sumList;
    }

    public void setValue(SalesPerformanceDataSheet__c sum , AggregateResult arg ,String field ){
        try{
            if(arg.get(field) != null )sum.put(field,arg.get(field));

        }catch(Exception e){

        }
    }
    public SalesPerformanceDataSheet__c generSumData(AggregateResult arg,String recordId,String year ,String quarter ){

        SalesPerformanceDataSheet__c sum = new SalesPerformanceDataSheet__c();
        sum.RecordTypeId = recordId;
        sum.put('Year__c', year);
        sum.put('Quarter__c',quarter);

        setValue(sum,arg,'InstrumentClasses__c');
        setValue(sum,arg,'Company__c');
        setValue(sum,arg,'EmployeeNumber__c');
        setValue(sum,arg,'Name__c');
        setValue(sum,arg,'JobCategory__c');
        setValue(sum,arg,'SalesMarket__c');

        setValue(sum,arg,'BudgetQuantity__c');
        setValue(sum,arg,'BudgetQuantityQ1__c');
        setValue(sum,arg,'BudgetQuantityQ2__c');
        setValue(sum,arg,'BudgetQuantityQ3__c');
        setValue(sum,arg,'BudgetQuantityQ4__c');

        setValue(sum,arg,'ActualQuantity__c');
        setValue(sum,arg,'ActualQuantityQ1__c');
        setValue(sum,arg,'ActualQuantityQ2__c');
        setValue(sum,arg,'ActualQuantityQ3__c');
        setValue(sum,arg,'ActualQuantityQ4__c');

        setValue(sum,arg,'LastYearSalesVolume__c');
        setValue(sum,arg,'LastYearSalesVolumeQ1__c');
        setValue(sum,arg,'LastYearSalesVolumeQ2__c');
        setValue(sum,arg,'LastYearSalesVolumeQ3__c');
        setValue(sum,arg,'LastYearSalesVolumeQ4__c');

        setValue(sum,arg,'IncrementalCcategory__c');
        setValue(sum,arg,'Category__c');
        setValue(sum,arg,'ReagentCategory__c');

        setValue(sum,arg,'ActualSales__c');
        setValue(sum,arg,'ActualSalesQ1__c');
        setValue(sum,arg,'ActualSalesQ2__c');
        setValue(sum,arg,'ActualSalesQ3__c');
        setValue(sum,arg,'ActualSalesQ4__c');

        setValue(sum,arg,'BudgetSales__c');
        setValue(sum,arg,'BudgetSalesQ1__c');
        setValue(sum,arg,'BudgetSalesQ2__c');
        setValue(sum,arg,'BudgetSalesQ3__c');
        setValue(sum,arg,'BudgetSalesQ4__c');
        
        return sum ;
    }
}